package cn.big.bigd.ybp.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import ch.qos.logback.core.net.SyslogOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.big.bigd.ybp.model.YbpRole;
import cn.big.bigd.ybp.model.YbpUser;
import cn.big.bigd.ybp.service.YbpUserService;
import cn.big.bigd.ybp.util.EmailUtils;
import cn.big.bigd.ybp.util.PasswordUtils;

/**
 * 
 * @author fan
 *
 */

@Controller
@RequestMapping("/ybp")
public class UserController{

	@Autowired
	YbpUserService userService;

	@RequestMapping("/password")
	public String passsword(@RequestParam("id") Long id, Model model) {
		model.addAttribute("id", id);
		return "ybp/password";
	}

	/**
	 * 重置密码
	 * 
	 * @param password
	 * @param newPassword
	 * @param confirmPassword
	 * @param id
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/passwordreset", method = RequestMethod.POST)
	public String updatePassword(@RequestParam("opassword") String password,
			@RequestParam("password") String newPassword, @RequestParam("cpassword") String confirmPassword,
			@RequestParam("id") Long id, ModelMap modelMap) {
		System.out.println(id);
		String message = "";
		try {
			userService.changePassword(password, newPassword, confirmPassword, id);
			message = "true";
		} catch (Exception e) {
			message = "false";
		}
		modelMap.put("message", message);
		return "ybp/password";
	}


	/**
	 * 用户登陆成功处理程序
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/success-login", method = RequestMethod.GET)
	public String successLogin(HttpSession httpSession, Model model) {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String email = userDetails.getUsername();

		YbpUser user = userService.findByEmail(email);
		// YbpUser user =(YbpUser)
		// SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		httpSession.removeAttribute("isadmin");
		httpSession.removeAttribute("issuperadmin");
		httpSession.setAttribute("loginuser", user);
		List<YbpRole> list = user.getRoleList();
		 System.out.println(user.getAuthorities().get(0));
		System.out.println(user.getRoleList().get(0));
         // user.getAuthorities()
		Boolean isadmin =false;
		Boolean issuperadmin =false;
		for (YbpRole role:list) {
			if (role.getId()==1){
				isadmin =true;

			}
			if (role.getId()==3){
				issuperadmin =true;

			}

		}
		if(issuperadmin) {

			httpSession.setAttribute("issuperadmin", issuperadmin);
			httpSession.setAttribute("isadmin", isadmin);
			return "redirect:/admin/home";
		}else if(isadmin){
			httpSession.setAttribute("isadmin", isadmin);
			return "redirect:/admin/home";
		}


		/*if (list.size() == 1) {
			YbpRole role = list.get(0);
			// admin
			if (role.getId() == 1) {
				httpSession.setAttribute("isadmin", "isadmin");
				return "redirect:/admin/home";
			}
			if (role.getId() == 3) {
				httpSession.setAttribute("issuperadmin", "issuperadmin");
				return "redirect:/admin/home";
			}
			if (role.getId() == 2) {
				model.addAttribute("user", user);
				return "ybp/info";
			}
		}*/
		model.addAttribute("user", user);
		return "ybp/info";
	}

	/**
	 * 修改用户信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(@RequestParam("id") Long id, Model model) {

		YbpUser user = userService.findById(id);
		model.addAttribute("user", user);

		return "ybp/info";

	}


	/**
	 * 上传图片请求
	 * 
	 * @param id
	 * @param file
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String handleUpload(@RequestParam("id") Long id, @RequestParam("file") MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		YbpUser user = userService.findById(id);
		String pathRoot = request.getSession().getServletContext().getRealPath("");
		System.out.println(pathRoot);
		String path = "/static/images/users/";
		String suffix = file.getContentType().substring(file.getContentType().indexOf("/") + 1);
		String picPath = path + user.getEmail().toLowerCase() + "." + suffix;
		String outPath = pathRoot + picPath;
		System.out.println(outPath);
		if (!file.isEmpty()) {
			try {
				BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outPath)));
				out.write(file.getBytes());
				out.flush();
				out.close();
				if (userService.updatePicPath(picPath, id) > 0) {
					model.put("image", "Image uploaded!");
				} else {
					model.put("image", "Image failed!");
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		user.setPicPath(picPath);
		model.addAttribute("user", user);
		return "ybp/info";
	}

	/**
	 * 更新用户信息请求
	 * 
	 * @param id
	 * @param username
	 * @param telephone
	 * @param department
	 * @param userType
	 * @param isInvited
	 * @param thirteenLunch
	 * @param thirteenDinner
	 * @param twelveDinner
	 * @param reportTitle
	 * @param reportAbstract
	 * @param userSummary
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateUser(@RequestParam("id") Long id, @RequestParam("username") String username,
			@RequestParam("telephone") String telephone, @RequestParam("department") String department,
			@RequestParam("userType") String userType, @RequestParam("isInvited") Integer isInvited,

			@RequestParam("thirteenLunch") Integer thirteenLunch,String [] roleID, Integer thirteenDinner, Integer twelveDinner,String issue,
			String reportTitle, String reportAbstract, String userSummary,HttpSession httpSession, ModelMap modelMap) {

		YbpUser user = userService.findById(id);
		user.setUsername(username);
		user.setTelephone(telephone);
		user.setDepartment(department);
		user.setUserType(userType);
		user.setIsInvited(isInvited);
		user.setThirteenLunch(thirteenLunch);
		if (userType.equals("PI/Senior Scientist")) {
			user.setThirteenDinner(thirteenDinner);
			
			user.setTwelveDinner(twelveDinner);
			user.setIssue(issue);
			if (isInvited == 0) {
				user.setReportTitle(reportTitle);
				user.setReportAbstract(reportAbstract);
				user.setUserSummary(userSummary);
			}
		}else{
			user.setIsInvited(1);
			user.setThirteenDinner(1);
			user.setTwelveDinner(1);
			user.setIssue("");
			user.setReportTitle("");
			user.setReportAbstract("");
			user.setUserSummary("");
		}
		if (httpSession.getAttribute("issuperadmin")!=null){
			user.setYbpRoleList(user.getYbpRoleList());
			if(roleID.length>0){
				user.getYbpRoleList().clear();
			}
			for (int i=0;i<roleID.length;i++){
				System.out.println(roleID[i]);
				if(1==Integer.valueOf(roleID[i])){
					System.out.println("323232323");
					user.addRole(YbpRole.ADMIN);
				}else if(2==Integer.valueOf(roleID[i])){
					user.addRole(YbpRole.USER);
				}else if(3==Integer.valueOf(roleID[i])){
					user.addRole(YbpRole.SUPERADMIN);
				}

			}
			
		}

		userService.save(user);
		modelMap.put("user", user);
		modelMap.put("message", "更新成功!");

		return "ybp/info";
	}

}
